package com.hcm.kernel.spring;

import com.hcm.kernel.util.HCMConstants;
import com.hcm.kernel.util.StringUtil;
import com.hcm.kernel.web.annotation.WebToken;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.support.HandlerMethodResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;

/**
 * session 拦截器
 */
public class HCMSessionInterceptor extends HandlerInterceptorAdapter {
    private String []excludes;//不使用过滤器的部分，可以不登录使用的内容，需要在spring-mvc中进行配置

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String contextPath = request.getContextPath();

        String url = request.getRequestURI();
        String referer = request.getHeader("Referer");//获取地址来源，如果是在地址栏直接输入，那么这个值就为空，否则是从连接过来

        //对登录情况校验
        //如果在地址栏直接输入login.shtml，那么要进行跳转
        if(StringUtil.isBlank(referer) && url.indexOf("login.htm")!=-1) {
            response.sendRedirect(contextPath + "/index.jsp");
            return false;
        }

        HttpSession session = request.getSession();
        Object objUser = session.getAttribute(HCMConstants.SESSION_USER);
        if(objUser == null){//未登录，或者登录超时
            for(String exclude:excludes){
                if(url.startsWith(contextPath+exclude)){ //不过滤内容
                    return true;
                }else{
                    continue;
                }
            }//需要登陆的跳转
            response.sendRedirect(contextPath+"/index.jsp");
            return false;
        }

        //下面将对表单重复提交作校验
//        Class handlerClass = ClassUtils.getUserClass(handler);
//        HandlerMethodResolver resolver = new HandlerMethodResolver();
//        resolver.init(handlerClass);
//        Set<Method> handlerMethods = resolver.getHandlerMethods();
//        for(Method method:handlerMethods){
//            RequestMapping mapping = method.getAnnotation(RequestMapping.class);
//            String mUrl = mapping.value()[0];
//            if(url.endsWith(mUrl+".htm")){
//                WebToken annotation = method.getAnnotation(WebToken.class);
//                if (annotation != null) {
//                    boolean needSaveSession = annotation.add();
//                    if (needSaveSession) {
//                        if(request.getSession(false)!=null)
//                            request.getSession(false).setAttribute("token", UUID.randomUUID().toString());
//                    }
//                    boolean needRemoveSession = annotation.valid();
//                    if (needRemoveSession) {
//                        if (isRepeatSubmit(request)) {//如果是重复提交，则直接跳转到提示页面。
//                            request.setAttribute("referer",referer);
//                            request.getRequestDispatcher("/common/info.jsp").forward(request,response);
//                            return false;
//                        }
//                        request.getSession(false).removeAttribute("token");
//                    }
//                }
//                return true;
//            }else{
//                continue;
//            }
//        }

        return super.preHandle(request, response, handler);
    }

    public void setExcludes(String[] excludes) {
        this.excludes = excludes;
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clientToken = request.getParameter("token");
        if (clientToken == null) {
            return true;
        }
        if (!serverToken.equals(clientToken)) {
            return true;
        }
        return false;
    }
}
